package com.nettyAdvanced.p2_short;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author： pang-yun
 * @date： 2021-09-14 16:39
 * 功能目的 ：用于  短连接 解决 黏包 现象  但是无法解决半包现象
 * <p>
 * <p>
 * .channel(NioServerSocketChannel.class)
 * //调整系统的 接收缓冲区 （滑动窗口）
 * //.option(ChannelOption.SO_RCVBUF,10)
 * //调整 ByteBuf     netty的接收缓冲区    默认是1024   最小是16   不能调的比16 小
 * .childOption(ChannelOption.RCVBUF_ALLOCATOR,new AdaptiveRecvByteBufAllocator(16,16,16))
 * 将 netty 的缓冲区 调整到比 要输入的数据小   就会出现半包现象！
 * adaptive   /əˈdæptɪv/  适应性的
 */

public class ShortServer {


    public static void main(String[] args) {
        start();
    }

    private static void start() {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup work = new NioEventLoopGroup();

        try {
            ChannelFuture channelFuture = new ServerBootstrap()
                    .group(boss, work)
                    .channel(NioServerSocketChannel.class)
                    //调整系统的 接收缓冲区 （滑动窗口）
                    //.option(ChannelOption.SO_RCVBUF,10)
                    //调整 ByteBuf     netty的接收缓冲区    默认是1024   最小是16   不能调的比16 小
                    .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(16, 16, 16))
                    .childHandler(
                            new ChannelInitializer<NioSocketChannel>() {
                                @Override
                                protected void initChannel(NioSocketChannel ch) throws Exception {
                                    ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                                    System.out.println("****************** result ********************");
                                }
                            }
                    ).bind(9999).sync();

            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            System.out.println("error");
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }
}
